package com.example.healthcode2.Fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import com.example.healthcode2.Object.UserMsg;

import com.example.healthcode2.Other.Ohuang;
import com.example.healthcode2.R;
import com.example.healthcode2.fillinfoActivity;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;


import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;


public class oneFragment extends Fragment {
    private View view;
    private Button button;
    private ImageView imageView;
    private TextView text_username, text_tips;
    private IntoListener intoListener;
    private String name;
    private final static int JSON_OK = 2;
    private final static int JSON_ERROR = 3;
    private final static int COLOR_ERROR = 4;
    private final static int COLOR_OK = 5;
    private UserMsg usermsg = null;


    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        intoListener = (IntoListener) context;
    }

    public oneFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        name = intoListener.Getnameforone();
        view = inflater.inflate(R.layout.fragment_one, container, false);
        initView();
        return view;
    }
//初始化组件
    private void initView() {
        button = view.findViewById(R.id.one_btn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), fillinfoActivity.class);
                intent.putExtra("name", name);
                startActivity(intent);
            }
        });
        text_username = view.findViewById(R.id.one_text_name);
        text_tips = view.findViewById(R.id.one_text_tips);
        imageView = view.findViewById(R.id.one_image_QRcode);



        HttpRequest();
    }
//获取用户数据
    private void HttpRequest() {
        RequestQueue queue = Volley.newRequestQueue(getContext());
        String url = "http://30r97104b2.qicp.vip/user/find";
        StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        Gson gson = new Gson();
                        Type type = new TypeToken<UserMsg>() {
                        }.getType();
                        usermsg = gson.fromJson(s, type);
                        myHandler.sendEmptyMessage(JSON_OK);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        myHandler.sendEmptyMessage(JSON_ERROR);
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("username", name);
                return params;
            }
        };
        queue.add(request);

    }
//获取健康码颜色
    private void httpGetColor(){
        RequestQueue queue = Volley.newRequestQueue(getContext());
        String url = "http://30r97104b2.qicp.vip/user/color";
        StringRequest request = new StringRequest(Request.Method.POST, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                       Message message=new Message();
//                       Bundle bundle = new Bundle();
//                       bundle.putString("co",s);
//                       message.setData(bundle);
                        message.obj=s;
                       message.what=COLOR_OK;
                        myHandler.sendMessage(message);

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        myHandler.sendEmptyMessage(COLOR_ERROR);
                        System.out.println("httpGetColor-volleyError");
                    }
                }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("username", name);
                return params;
            }
        };
        queue.add(request);
    }


    @SuppressLint("HandlerLeak")
    private Handler myHandler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case JSON_OK:
                    text_username.setText(usermsg.getName1() + "");
                    httpGetColor();
                    break;
                case JSON_ERROR:
                    Toast.makeText(getContext(), "网络异常", Toast.LENGTH_SHORT).show();
                    break;

                case COLOR_OK:
                    String a= (String) msg.obj;
                    showHealthCode(a);
                    break;

                case COLOR_ERROR:
                    Toast.makeText(getContext(), "健康码数据获取失败", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
//显示健康码
    private void showHealthCode(String co){
        switch (co){
            case "g":
                text_tips.setText("绿色码:凭此码可出行在公共场所,请主动出示，配合检查。");
                String aa = usermsg.toString();//二维码内的信息
                //生成健康码
                Bitmap bitmap = Ohuang.createQRCodeBitmap(aa, 400, 400, "UTF-8",
                        null, null, Color.rgb(0, 190, 0), Color.WHITE);

                imageView.setImageBitmap(bitmap);
                break;
            case "y":
                text_tips.setText("黄色码:请不要在公共场所活动，需要在家隔离记得多喝热水。");
                String bb = usermsg.toString();//二维码内的信息
                //生成健康码
                Bitmap bitmap2 = Ohuang.createQRCodeBitmap(bb, 400, 400, "UTF-8",
                        null, null, Color.rgb(190, 190, 0), Color.WHITE);
                imageView.setImageBitmap(bitmap2);
                break;
            case "r":
                text_tips.setText("红色码:为了你的健康，请去医院进行核酸检查。");
                String cc = usermsg.toString();//二维码内的信息
                //生成健康码
                Bitmap bitmap3 = Ohuang.createQRCodeBitmap(cc, 400, 400, "UTF-8",
                        null, null, Color.rgb(190, 0, 0), Color.WHITE);
                imageView.setImageBitmap(bitmap3);
                break;
        }
    }
    //定义接口
    public interface IntoListener {
        String Getnameforone();
    }
}
